module('round', package.seeall)

local currentRound = ROUND_BUILD
local roundStart = 0
local roundEvents = {}

-- Public Functions

function AddEvent(iRoundID, callback)
	if type(iRoundID) != "number" then error("round.AddEvent - First argument needs to be a number!") end
	if type(callback) != "function" then error("round.AddEvent - Second argument needs to be a function!") end
	
	print("Adding Event to "..iRoundID.."["..tostring(callback).."]")
	
	table.insert(roundEvents, {iRoundID, callback})
end

function CallEvents(iRoundID)
	if type(iRoundID) != "number" then error("round.CallEvents - First argument needs to be a number!") end

	print(CLIENT and "Client:".."Calling Events: "..iRoundID or SERVER and "Server:".."Calling Events: "..iRoundID)
	
	PrintTable(roundEvents)
	
	for _, v in pairs(roundEvents) do
		if v[1] == iRoundID then v[2]() end
	end
end

function RoundTime()
	if currentRound == ROUND_BUILD then return GAME_BUILD_TIME*60 end
	if currentRound == ROUND_FIGHT then return GAME_FIGHT_TIME*60 end
	if currentRound == ROUND_OVER then return GAME_OVER_TIME*60 end
	
	return 0
end

function RemainingTime()
	return RoundTime()-(CurTime() - roundStart)
end

function CurrentRound()
	return currentRound
end

function NextRound()
	if currentRound == ROUND_BUILD then return ROUND_FIGHT end
	if currentRound == ROUND_FIGHT then return ROUND_OVER end
	if currentRound == ROUND_OVER then return ROUND_BUILD end
end

-- Private Functions

local function Tick()
	if RemainingTime() <= 0 then
		CallEvents(NextRound())
		currentRound = NextRound()
		roundStart = CurTime()
	end
end

timer.Create("FloodTickTimer", 1, 0, Tick)

if CLIENT then
	local function SetRound(um)
		local round = um:ReadChar()
		local timeLeft = um:ReadShort()
		
		roundStart = CurTime()-(RoundTime()-timeLeft)
		currentRound = round
		CallEvents(round)
	end
	usermessage.Hook("flood_setround", SetRound)
end


-- THIS FUNCTIONS MESSES UP SOMEHOW. IDK :S
if SERVER then

-- IF DEBUG THEN
	concommand.Add("FD_NextRound", function()
		roundStart = CurTime()
		currentRound = NextRound()
		CallEvents(currentRound)
	
		umsg.Start("flood_setround")
			umsg.Char(currentRound)
			umsg.Short(RemainingTime())
		umsg.End()
	end)
-- END

end